package com.learning.mybatis.function;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DecryptEncryptUtils {
    //这里设置自己的加减密key
    private static final String key = "";

    /**
     * 加密
     *
     * @return
     * @paramtext
     * @paramkey
     */
    private static String sm4Encrypt(String text, String key) {
        SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes());
        return sm4.encryptBase64(text);
    }

    /**
     * 解密
     *
     * @return
     * @paramhexString
     * @paramkey
     */
    private static String sm4Decrypt(String hexString, String key) {
        try {
            SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes());
            return sm4.decryptStr(hexString, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
//解密失败，直接返回明文，不影响业务进程
            return hexString;
        }
    }

    public static String sm4Encrypt(String text) {
        return sm4Encrypt(text, key);
    }

    public static String sm4Decrypt(String hexString) {
        return sm4Decrypt(hexString, key);
    }
}
